package cn.js189.redis;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.ctg.itrdc.cache.pool.CtgJedisPool;
import com.ctg.itrdc.cache.pool.CtgJedisPoolConfig;
import com.ctg.itrdc.cache.pool.CtgJedisPoolException;
import com.ctg.itrdc.cache.vjedis.jedis.JedisPoolConfig;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;

import java.util.ArrayList;
import java.util.List;

/**
 * ctg-redis配置
 */
@Configuration
@EnableCaching
@AutoConfigureBefore(RedisCache.class)
public class RedisConfig{

    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Value("${redis.cluster.nodes}")
    private String clusterNodes;

    //    @Value("${spring.redis.cluster.max-redirects}")
//    private int maxRedirects;

    @Value("${redis.maxTotal}")
    private int maxTotal;

    @Value("${redis.pool.max-idle}")
    private int maxIdle;

    @Value("${redis.pool.min-idle}")
    private int minIdle;

    @Value("${redis.pool.max-wait}")
    private long maxWaitMillis;

    @Value("${redis.password}")
    private String password;

    public CtgJedisPool createCtgJedisPool() {
        logger.info("----创建ctg-cache连接池开始----");
        CtgJedisPool pool = null;
        // 接入机地址列表
        List<HostAndPort> hostAndPortList = new ArrayList<>(1);
        try {
            List<String> serverNodes = CharSequenceUtil.split(clusterNodes,",");
            if(CollUtil.isNotEmpty(serverNodes)){
                for (String ipPort : serverNodes) {
                    String[] ipAndPort = ipPort.split(":");
                    hostAndPortList.add(new HostAndPort(ipAndPort[0].trim(), Integer.parseInt(ipAndPort[1])));
                }
                GenericObjectPoolConfig poolConfig = new JedisPoolConfig(); //线程池配置
                poolConfig.setMaxTotal(maxTotal); // 最大连接数（空闲+使用中）
                poolConfig.setMaxIdle(maxIdle); //最大空闲连接数
                poolConfig.setMinIdle(minIdle); //保持的最小空闲连接数
                poolConfig.setMaxWaitMillis(maxWaitMillis); //借出连接时最大的等待时间
                CtgJedisPoolConfig config = new CtgJedisPoolConfig(hostAndPortList);
                config.setDatabase(10) //分组对应的桶位
                        .setPassword(password) // “用户#密码”
                        .setPoolConfig(poolConfig) //线程池配置
                        .setPeriod(5000)  //后台监控执行周期，毫秒
                        .setMonitorLog(false)
                        .setMonitorTimeout(1000);  //后台监控ping命令超时时间,毫秒
                pool = new CtgJedisPool(config); //创建连接池
            }else{
                logger.info("redis节点配置为空，请检查");
            }

        } catch (CtgJedisPoolException e) {
            logger.error("----创建ctg-cache连接池失败----，{}",e.getMessage(),e);
        } catch (Exception e){
            logger.error("----创建ctg-cache连接池出现异常----{}",e.getMessage(),e);
        }
        return pool;
    }


}
